package com.matt.controller.group.staffExtend;

import com.alibaba.fastjson.JSON;
import com.dotflat.staffExtend.domain.StaffExtendInfo;
import com.dotflat.staffExtend.dto.StaffExtendInfoListDTO;
import com.dotflat.staffExtend.po.GroupStaffExtendInfoPO;
import com.dotflat.staffExtend.po.StaffExtendInfoPO;
import com.dotflat.staffExtend.repository.StaffExtendInfoRepository;
import com.dotflat.staffExtend.service.StaffExtendInfoService;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.model.StatusResponse;
import com.matt.commons.page.PagerQuery;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.utils.DateUtil;
import com.matt.service.remoteCall.DTO.SsoAreaDTO;
import com.matt.service.remoteCall.SsoCallService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.matt.foundation.constant.RequestConstant.TICKET;

@RestController
@RequestMapping("/web/group/staff_extend/info")
@Slf4j
@Api(tags = "Web集团 - 员工扩展信息 - 详情")
public class WebGroupStaffExtendInfoController  {

    @Autowired
    private StaffExtendInfoService baseService;

    @Autowired
    protected MemVerificationCache cache;

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private StaffExtendInfoRepository infoRepository;

    @ApiOperation(value = "获取集团老师档案联合列表", response = StaffExtendInfoListDTO.class)
    @GetMapping("/list_join")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "status", value = "状态", defaultValue = "-1", required = false, dataType = "int"),
    })
    public StatusResponse getList(@RequestHeader(TICKET) String ticket, String realName, String areaId, String roleId, Integer status ,PagerQuery pagerQuery){
        StaffDTO staff = cache.getStaff(ticket);
        if (Objects.isNull(status)){
            status = -1;
        }

        Map pageMap = ssoCallService.getGroupAllStaff(ticket, areaId, roleId, realName, pagerQuery.getPageNum(), pagerQuery.getPageSize());

        //这里是因为无法自动转PageImpl
        List<Map<String, String>> content = (List) pageMap.get("content");
        if (content == null || content.size() == 0) {
            StatusResponse.success(pageMap);
        }

        content.stream().forEach(o->{

        });

        List<String> staffIds = content.stream().map(o->(String)o.get("id")).collect(Collectors.toList());

        //处理扩展信息
//        List<String> staffIds = staffs.stream().map(StaffExtendInfoListDTO::getStaffId).collect(Collectors.toList());
        List<StaffExtendInfo> extendInfos = infoRepository.findAllByAreaIdAndStaffIdIn(staff.getAreaId(), staffIds);
        Map<String, StaffExtendInfo> cache = extendInfos.stream().collect(Collectors.toMap(StaffExtendInfo::getStaffId, o->o));

        content.stream().forEach(o->{
            String staffId = o.get("id");
            StaffExtendInfo info = cache.get(staffId);
            if (info != null) {
//                o.setExtendInfoId(info.getId());
//                o.setPosition(info.getPosition());
//                o.setBirthday(info.getBirthday());
//                o.setJoinAt(info.getJoinAt());
                o.put("extendInfoId",info.getId());
                o.put("position",info.getPosition());
                if (info.getBirthday() != null)
                    o.put("birthday", DateUtil.formatDayToStr(info.getBirthday()));
                if (info.getJoinAt() != null)
                    o.put("joinAt", DateUtil.formatDayToStr(info.getJoinAt()));
            }

            //TODO：这里需要修改
            String mobile = o.get("mobile");
            o.put("rankVal", (Integer.parseInt(mobile.substring(mobile.length() - 1)) % 6) + "");
        });

        //处理评分信息
        //TODO:需要变更评分逻辑

        return StatusResponse.success(pageMap);
    }

    @ApiOperation(value = "增加一条记录")
    @PostMapping()
    public StatusResponse add(@RequestHeader(TICKET) String ticket, StaffExtendInfoPO param){
        StaffDTO staff = cache.getStaff(ticket);

        List<SsoAreaDTO> areaDTOList = ssoCallService.getGroupAllArea(ticket);

        Optional<SsoAreaDTO> anyArea = areaDTOList.stream().filter(o->o.getId().equals(param.getAreaId())).findFirst();
        if (!anyArea.isPresent()){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "指定园区不存在");
        }

        String id = param.getStaffId();

        StaffDTO newStaff = null;

        if (StringUtils.isBlank(id)){
            //新建一个用户
            newStaff = new StaffDTO();
            newStaff.setGender(param.getGender());
            newStaff.setRealName(param.getRealName());
            newStaff.setHeadImgUrl(param.getHeadImgUrl());
            newStaff.setMobile(param.getMobile());
            newStaff.setLastLogin(0L);
            newStaff.setAreaId(param.getAreaId());

            if (StringUtils.isNotEmpty(param.getRoleId())){
                newStaff = ssoCallService.createStaff(ticket, newStaff, new String[]{param.getRoleId()});
            }else{
                newStaff = ssoCallService.createStaff(ticket, newStaff);
            }

            return StatusResponse.success(newStaff);
        }else{
            newStaff = new StaffDTO();

            newStaff.setId(id);
            newStaff.setGender(param.getGender());
            newStaff.setRealName(param.getRealName());
            newStaff.setHeadImgUrl(param.getHeadImgUrl());
            newStaff.setMobile(param.getMobile());
            newStaff.setLastLogin(0L);
            newStaff.setAreaId(param.getAreaId());

            newStaff = ssoCallService.updateStaff(ticket, newStaff);
        }

        if (newStaff == null){
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "指定员工不存在");
        }

        param.setStaffId(newStaff.getId());

        //找到是否存在对应的档案
        StaffExtendInfo exist = infoRepository.findFirstByAreaIdAndStaffId(param.getAreaId(), newStaff.getId());
        if (exist != null){
            param.setId(exist.getId());
        }

        StaffExtendInfo ret = baseService.add(param.getAreaId(), staff.getId(), param);

        return StatusResponse.success(ret);
    }

    @ApiOperation(value = "获取列表")
    @GetMapping("/list")
    public StatusResponse getList(@RequestHeader(TICKET) String ticket, StaffExtendInfoPO param, PagerQuery pagerQuery){
        StaffDTO staff = cache.getStaff(ticket);

        List<SsoAreaDTO> areaDTOList = ssoCallService.getGroupAllArea(ticket);
        List<String> ids = areaDTOList.stream().map(o->o.getId()).collect(Collectors.toList());

        GroupStaffExtendInfoPO groupParam = GroupStaffExtendInfoPO.of(param, GroupStaffExtendInfoPO.class);
        if (StringUtils.isBlank(groupParam.getAreaId())){
            groupParam.setAreaId(null);
            groupParam.setAreaIds(ids);
        }else{
            Optional<SsoAreaDTO> anyArea = areaDTOList.stream().filter(o->o.getId().equals(groupParam.getAreaId())).findFirst();
            if (!anyArea.isPresent()){
                throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "指定园区不存在");
            }
        }

        Sort sort = null;

        Field[] fields = param.getClass().getDeclaredFields();
        if (fields != null && fields.length > 0){
            for (Field f: fields){
                if ("sort".equals(f.getName())){
                    sort = Sort.by("sort", "created").descending();
                    break;
                }
            }
        }
        if (sort == null){
            sort = Sort.by("created").descending();
        }

        PageRequest pageRequest = PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize(), sort);

        return StatusResponse.success( baseService.page(null, staff.getId(), groupParam, pageRequest));
    }

}
